#include <mongoose.h>
#include <gwbase/base/util.h>
#include <gwbase/base/logging.h>
#include <assert.h>

using namespace dicom;

struct mg_server* server = NULL;

int mg_handler(struct mg_connection* conn, enum mg_event ev) {
  // LOG_INFO << "recv event: " << ev;

  struct mg_connection* upstream = NULL;
  struct mg_connection* orig = NULL;
  switch (ev) {
    case MG_AUTH:
      return MG_TRUE;

    case MG_REQUEST:
      assert(conn->connection_param == NULL);
      upstream = ::mg_connect(server, "ssl://www.surdoc.com:443::ca.pem");
      if (upstream != NULL) {
        conn->connection_param = upstream;
        upstream->connection_param = conn;
        printf("Conencted to backend: %p\n", upstream);
        return MG_MORE;
      } else {
        ::mg_send_status(orig, 500);
        return MG_TRUE;
      }

    case MG_CONNECT:
      printf("Conencted to backend for orig: %p\n", conn->connection_param);
      mg_printf(conn, "GET %s HTTP/1.0\r\nHost: %s\r\n\r\n", "/index.html",
                "www.surdoc.com");
      return MG_TRUE;

    case MG_REPLY:
      printf("receved reply: %p\n", conn->connection_param);
      orig = static_cast<struct mg_connection*>(conn->connection_param);
      assert(orig != NULL);
      for (int i = 0; i < conn->num_headers; ++i) {
        ::mg_send_header(orig, conn->http_headers[i].name,
                         conn->http_headers[i].value);
      }
      ::mg_send_data(orig, conn->content, static_cast<int>(conn->content_len));
      ::mg_send_data(orig, "", 0);
      orig->connection_param = NULL;
      conn->connection_param = NULL;
      return MG_TRUE;
    case MG_CLOSE:
    default:
      return MG_FALSE;
  }
  return MG_FALSE;
}

int main() {
  server = ::mg_create_server(NULL, &mg_handler);

  ::mg_set_option(server, "listening_port", Fmt("%d", 3322).c_str());

  while (true) {
    if (::mg_poll_server(server, 1000) < 0) break;
  }

  return 0;
}
